package org.dsun.mvc.filter;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dsun.mvc.config.ActionConfig;
import org.dsun.mvc.entity.Action;
import org.dsun.reflect.Seter;

public class GlobalDistributeFilterUtil {
	
	public static void DistributeByConfig(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain, FilterConfig config)
			throws InstantiationException, IllegalAccessException,
			ClassNotFoundException, IllegalArgumentException,
			SecurityException, InvocationTargetException, NoSuchMethodException {
		String url=request.getServletPath();
		Action action=findActionByURL(url);
		Object runAction=Class.forName(action.getActionClass()).newInstance();
		Seter.invokeSeter(runAction, "request", request);
		Seter.invokeSeter(runAction, "response", response);
		runAction.getClass().getMethod(action.getActionMethod()).invoke(runAction);
		action.getResult().afterAction(runAction, request, response, chain);
	}

	private static Action findActionByURL(String url){
		//TODO 这里还要分是否注重路径
		ActionConfig ac=ActionConfig.getInstance();
		Map<String,Action>actions=ac.getActions();
		for(String u:actions.keySet()){
			if(u.charAt(0)=='/'){
				if((u+".sun").equals(url)){
					return actions.get(u);
				}
			}else{
				if(url.endsWith("/"+u+".sun")){
					return actions.get(u);
				}
			}
		}
		return null;
	}
}
